﻿using System.Collections.Generic;
using Microsoft.Phone.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Shell;

namespace BalanceManager.Helpers
{
    public class BindablePage : PhoneApplicationPage
    {
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            
            var navigableViewModel = DataContext as INavigable;
            if (navigableViewModel != null)
            {
                var objectParameters = new Dictionary<string, object>(ApplicationController.Default.NavigationParameters);
                navigableViewModel.Activate(objectParameters);
                ApplicationController.Default.NavigationParameters = null;
            }
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);

            var navigableViewModel = DataContext as INavigable;
            if (navigableViewModel != null)
            {
                var dict = new Dictionary<string, object>();
                navigableViewModel.Deactivate(dict);
                PhoneApplicationService.Current.State.Clear();
                foreach (var p in dict)
                {
                    if (PhoneApplicationService.Current.State.ContainsKey(p.Key))
                        PhoneApplicationService.Current.State[p.Key] = p.Value;
                    else
                        PhoneApplicationService.Current.State.Add(p.Key, p.Value);
                }
            }
        }
    }
}
